package common

import (
	"git.mycaigou.com/gfyx/common/authorize"
	"git.mycaigou.com/gfyx/common/rpc_client"
	"git.mycaigou.com/gfyx/micro-gfyx-api/http_server/controller"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/errcode"
	common_dto "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/common"
	"git.mycaigou.com/gfyx/micro-gfyx-api/service/common"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
)

type VerifyCodeController struct {
	controller.BaseController
	verifyCodeService common.VerifyCodeServiceIface
}

func NewVerifyCodeController(verifyCodeService common.VerifyCodeServiceIface) *VerifyCodeController {
	return &VerifyCodeController{
		verifyCodeService: verifyCodeService,
	}
}

func (v *VerifyCodeController) RegisterRouter(g *gin.RouterGroup) {
	// 展示图形验证码
	g.POST("/verify-code/show-captcha", v.showCaptcha)
	// 发送验证码
	g.POST("/verify-code/send-sms", v.sendSms)
}

// ShowCaptcha 显示验证码
func (v *VerifyCodeController) showCaptcha(ctx *gin.Context) {
	request := common_dto.GetCaptchaRequest{}
	if err := ctx.ShouldBind(&request); err != nil {
		v.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}
	ctx.Set(authorize.TENANT_CODE_KEY, request.TenantCode)

	// 生成验证码
	id, b64s, err := v.verifyCodeService.GetCaptcha(ctx)
	if err != nil {
		stark.Logger.Info(ctx, "show-captcha-failed: "+err.Error())
		grpcErr := rpc_client.GetGrpcError(err)
		stark.Logger.Errorf(ctx, "GenerateCaptcha-error:%+v", err)
		v.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}

	resp := &common_dto.GetCaptchaResponse{
		CaptchaId:    id,
		CaptchaImage: b64s,
	}

	v.Success(ctx, resp)
	return
}

// SendSms 发送验证码
func (v *VerifyCodeController) sendSms(ctx *gin.Context) {
	// todo 加上频率的限制
	request := common_dto.SendSmsRequest{}
	if err := ctx.ShouldBind(&request); err != nil {
		v.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}

	ctx.Set(authorize.TENANT_CODE_KEY, request.TenantCode)
	resp, err := v.verifyCodeService.SendSms(ctx, &request)
	if err != nil {
		stark.Logger.Info(ctx, "send-sms-failed: "+err.Error())
		grpcErr := rpc_client.GetGrpcError(err)
		stark.Logger.Errorf(ctx, "SendSms-error:%+v", err)
		v.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}

	v.Success(ctx, resp)
	return
}
